package com.cx.mall.pay.controller;

import com.cx.mall.common.model.order.OrderInfo;
import com.cx.mall.common.utils.ResponseVO;
import com.cx.mall.pay.config.AlipayConfiguration;
import com.cx.mall.pay.service.IAlipayService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import static com.alipay.api.AlipayConstants.CHARSET_UTF8;


@RestController
@RequestMapping("/alipay")
public class AlipayController {
    @Autowired
    private IAlipayService alipayService;
    @Autowired
    private AlipayConfiguration alipayConfiguration;
    @GetMapping("/pay")
    public void pay(OrderInfo orderInfo, HttpServletResponse response) throws Exception {
        // 调用业务
        String result = alipayService.pay(orderInfo);
        // 返回结果给前端:将表单直接输出到页面，用户点击后会跳转到支付宝支付页面
        response.setContentType("text/html;charset=" + CHARSET_UTF8);
        response.getWriter().write(result);
        response.getWriter().flush();
        response.getWriter().close();
    }
    @GetMapping("/return")
    public void payReturn(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 设置响应的字符编码为UTF-8，防止中文乱码
        response.setCharacterEncoding("UTF-8");
        // 设置响应的内容类型为HTML，并指定字符编码为UTF-8
        response.setContentType("text/html; charset=UTF-8");
        //查询支付日志，按照订单号，如果不存在就在写一次日志
        // 重定向到指定的HTML页面（需要提前与前端沟通好支付成功后要跳转的页面）
        response.sendRedirect(alipayConfiguration.getSuccessUrl());
    }
    @PostMapping("/notify")
    public void payNotify(HttpServletRequest request) {
        // 获取支付宝返回的各个参数
        Map<String, String[]> result = request.getParameterMap();
        // 检查交易状态是否为成功
        if ("TRADE_SUCCESS".equals(request.getParameter("trade_status"))) {
            // 通知处理
            alipayService.payNotify(result);
        }
    }
    @GetMapping("/success")
    public void success(HttpServletResponse response) throws IOException {
        // 跳转到指定的HTML页面（需要提前与前端沟通好支付成功后要跳转的页面）
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<html><head><title>支付成功</title></head><body>");
        out.flush();
        out.close();
    }

    /**
     * 查询支付回查结果
     * @param outTradeNo
     * @return
     * @throws Exception
     */
    @GetMapping("/query")
    public ResponseVO query(String outTradeNo) throws Exception {
        String result = alipayService.query(outTradeNo);
        return ResponseVO.success(result);
    }

}
